﻿using System;
using System.Threading;

namespace Kobets.Automation.Chimera.Common
{
    /// <summary>
    /// Forces single instance
    /// Used for AgentConfigurator so it would run only once
    /// </summary>
    public static class SingleInstance
    {
        public static readonly int WmShowfirstinstance = WinApi.RegisterWindowMessage("WM_SHOWFIRSTINSTANCE|{0}", ProgramInfo.AssemblyGuid);
        private static Mutex _mutex;

        public static bool Start()
        {
            bool onlyInstance;
            var mutexName = String.Format("Global\\{0}", ProgramInfo.AssemblyGuid);
            _mutex = new Mutex(true, mutexName, out onlyInstance);
            return onlyInstance;
        }

        public static void ShowFirstInstance()
        {
            WinApi.PostMessage((IntPtr)WinApi.HwndBroadcast, WmShowfirstinstance, IntPtr.Zero, IntPtr.Zero);
        }

        public static void Stop()
        {
            _mutex.ReleaseMutex();
        }
    }
}
